#! /usr/bin/env python
#coding:utf8

from xlrd import open_workbook

import os
import sys

# reload(sys)
# sys.setdefaultencoding('utf-8')

type = ['int','float','string']


def to_int(arg):
    # print int(arg)
    return int(arg)

def to_float(arg):
    # print arg
    return float(arg)

def to_string(arg):
    # print arg
    return arg

switch = {'int': to_int, 'float': to_float, 'string': to_string}

# switch[case](arg)

def outputTxt(curSheet,tableName):
    curtype = [];
    values = [];
    for row in range(curSheet.nrows):
        value = []
        for col in range(curSheet.ncols):
            value.append(curSheet.cell(row,col).value)
        if row == 1:
            curtype = value
        else:
            values.append(value)
            # print value
    # print curtype
    # print values    
    result = []
    for rowIndex in range(len(values)):
        row = values[rowIndex]

        if rowIndex == 0:
            result.append(row)
        else:
            tmp = []
            for colIndex in range(len(row)):
                # print curtype[colIndex] +  " => " + unicode(row[colIndex]) 
                switchvalue = switch.get(curtype[colIndex])(row[colIndex])
                tmp.append(switchvalue)
            # print tmp
            result.append(tmp) 
            
    # print result

    with open("%s.txt"%(tableName), "w+") as my_file:
        for rowIndex in range(len(result)):
            line = '\t'.join(unicode(v) for v in result[rowIndex]).encode('utf-8')
            if(rowIndex < (len(result)- 1)):
                my_file.write(line+'\n')
            else:
                my_file.write(line)


for curPath in os.listdir("."):
    if os.path.isfile(curPath) and os.path.splitext(curPath)[1] == '.xlsx':
        wb = open_workbook(curPath)
        outputTxt(wb.sheet_by_index(0), os.path.splitext(curPath)[0])
    if os.path.isfile(curPath) and os.path.splitext(curPath)[1] == '.xls':
        wb = open_workbook(curPath)
        outputTxt(wb.sheet_by_index(0), os.path.splitext(curPath)[0])


# eror1
# values = [50101.0, u'\u89c2\u661f\u8005', u'2|2|2|0']
# curStr = ';'.join(values)
# TypeError: sequence item 0: expected string, float found

# error2
# values = [50101.0, u'\u89c2\u661f\u8005', u'2|2|2|0']
# curStr = ';'.join(str(v) for v in values)
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
# cause u'\u89c2\u661f\u8005

# OK
# values = [50101.0, u'\u89c2\u661f\u8005', u'2|2|2|0']
# curStr = ';'.join(unicode(v) for v in values).encode('utf-8')

#最终抛弃了这个方案

# Excel treats all numbers as floats.
# 最终还是不行的 比如你填个 string 1 => 结果就变成 string 1.0了 这样不好 
# 但是如果统一成int 1 其实也不好 为什么有时候这里就是string 到时候说不定就要改的说
# 哎 抛弃这个方案了

# http://stackoverflow.com/questions/8825681/integers-from-excel-files-become-floats
# http://uucode.com/blog/2013/10/22/using-xlrd-and-formatting-excel-numbers/
